﻿using CommunityToolkit.Mvvm.ComponentModel;
using QModels;
using QServices.Services;
using QServices;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using HandyControl.Data;
using Microsoft.Extensions.DependencyInjection;
using MiniExcelLibs;
using System.Windows.Forms;
using TouchSocket.Core;

namespace QControlCenter.ViewModel;

public partial class PigeonPageCardViewModel:QBaseVM
{

	#region 鸽笼监控

	/// <summary>
	/// 鸽笼管理
	/// </summary>
	[ObservableProperty]
	private int geLongGuanLi;

	/// <summary>
	/// 空置鸽笼
	/// </summary>
	[ObservableProperty]
	private int kongZhigeLong;

	/// <summary>
	/// 查蛋
	/// </summary>
	[ObservableProperty]
	private int chaDan;

	/// <summary>
	/// 照蛋
	/// </summary>
	[ObservableProperty]
	private int zhaoDan;

	/// <summary>
	/// 查雏
	/// </summary>
	[ObservableProperty]
	private int chaChu;

	/// <summary>
	/// 出栏
	/// </summary>
	[ObservableProperty]
	private int chuLan;

	/// <summary>
	/// 淘汰
	/// </summary>
	[ObservableProperty]
	private int taoTai;

	/// <summary>
	/// 补栏
	/// </summary>
	[ObservableProperty]
	private int buLan;

	/// <summary>
	/// 调并
	/// </summary>
	[ObservableProperty]
	private int tiaoBing;

	/// <summary>
	/// 健康检查
	/// </summary>
	[ObservableProperty]
	private int jianKangJianCha;

	[ObservableProperty]
	private int tempErr;

	#endregion

	[ObservableProperty]
	private decimal maxPageCount;



	[ObservableProperty]
	private int? region;
	[ObservableProperty]
	private string? cageNumber;
	[ObservableProperty]
	private int? hasRuGe;
	[ObservableProperty]
	private int? hasDan;
	[ObservableProperty]
	private int? wenDu;
	[ObservableProperty]
	private int cageStatus;
	[ObservableProperty]
	private int pageIndex;

	public ObservableCollection<PigeonCageQuery> PigeonCages { get; set; } = new ObservableCollection<PigeonCageQuery>();
	public ObservableCollection<AreaModel> AreaModels { get; set; } = new ObservableCollection<AreaModel>
		{
				new AreaModel{Name="全部",Value=""},
				new AreaModel{Name="A区",Value="A"},
				new AreaModel{Name="B区",Value="B"},
				new AreaModel{Name="C区",Value="C"},
				new AreaModel{Name="D区",Value="D"},
				new AreaModel{Name="E区",Value="E"}
		};
	public string[] AreaArray = new string[] { "", "A", "B", "C", "D", "E" };
	public ObservableCollection<UseModel> HasOrNoArray { get; set; } = new ObservableCollection<UseModel>
		{
			new UseModel{Name="全部",Value=0},
			new UseModel{Name="无",Value=1},
			new UseModel{Name="有",Value=2}
		};

	public ObservableCollection<UseModel> WenDus { get; set; } = new ObservableCollection<UseModel>
		{
			new UseModel{Name="全部",Value=0},
			new UseModel{Name="正常温度",Value=1},
			new UseModel{Name="异常温度",Value=2}
		};
	public ObservableCollection<UseModel> CageStatusList { get; set; } = new ObservableCollection<UseModel>
		{
			new UseModel{Name="所有",Value=0},
			new UseModel{Name="空置鸽笼",Value=1 },
			new UseModel{Name="查蛋",Value=2},
			new UseModel{Name="照蛋",Value=3},
			new UseModel{Name="查雏",Value=4},
			new UseModel{Name="出栏",Value=5},
			new UseModel{Name="淘汰",Value=6},
			new UseModel{Name="补栏",Value=7},
			new UseModel{Name="调并",Value=8},
			new UseModel{Name="健康检测",Value=9}
		};
	private static int PageSize { get; set; } = 50;
	public void InitData()
	{
		var regionIndex = Region.HasValue ? Region.Value : 0; if (regionIndex < 0) regionIndex = 0;
		var areaName = AreaArray[regionIndex];
		var dto = AppRuntime.GetService().GetService<PigeonCageService>().GetPigeCageDtoProce(areaName);

		GeLongGuanLi = dto.GeLongGuanLi;
		JianKangJianCha = dto.JiangKangJianCha;
		ChaDan = dto.ChaDan;
		ZhaoDan = dto.ZhaoDan;
		ChaChu = dto.ChaChu;
		ChuLan = dto.ChuLan;
		TaoTai = dto.TaoTai;
		TiaoBing = dto.TiaoBing;
		BuLan = dto.BuLan;
		KongZhigeLong = dto.KongZhigeLong;
		TempErr = dto.TempErr;
	}

	public PigeonPageCardViewModel()
	{
		HasDan = 0;
		HasRuGe = 0;
		Region = 0;
		MaxPageCount = 10;
		PageIndex = 1;
		InitData();
		QueryCage();
	}


	[RelayCommand]
	public async Task QueryCage()
	{

		var regionIndex = Region.HasValue ? Region.Value : 0; if (regionIndex < 0) regionIndex = 0;
		var hasegg = HasDan.HasValue ? HasDan.Value : 0; if (hasegg < 0) hasegg = 0;
		var haschild = HasRuGe.HasValue ? HasRuGe.Value : 0; if (haschild < 0) haschild = 0;
		var haswendu = WenDu.HasValue ? WenDu.Value : 0; if (haswendu < 0) haswendu = 0;
		var condition = new PigeonCondition
		{
			Region = AreaArray[regionIndex],
			CageNumber = CageNumber,
			CageStatus = CageStatus,
			HasEgg = hasegg,
			HasRuGe = haschild,
			TempStatus = haswendu

		};

		var res = AppRuntime.GetService().GetService<PigeonCageService>().GetPigeonCageQueryList(condition, PageIndex, PageSize);
		MaxPageCount = (res.total + PageSize - 1) / PageSize;
		if (PigeonCages.Count > 0) PigeonCages.Clear();
		res.lst.ForEach(x =>
		{
			x.background = "#0000";
			if (!string.IsNullOrWhiteSpace(x.Temperature))
			{
				var arr = x.Temperature.Replace("[", "").Replace("]", "").Replace("'", "").Replace("\"", "").Split(new string[] { ",", "，" }, StringSplitOptions.RemoveEmptyEntries).Select(x => decimal.Parse(x));
				if (arr.Any(m => m > AppRuntime.MaxTemperature || m < AppRuntime.MinTemperature)) x.IsAbnormal = true;
				if (x.IsAbnormal)
				{
					x.background = "red";
				}
			}
			if (x.F1 != x.FT1 || x.F2 != x.FT2 || x.F3 != x.FT3) x.background = "red";
			PigeonCages.Add(x);
		});
		InitData();
	}


	[RelayCommand]

	public void OutportCage()
	{
		var regionIndex = Region.HasValue ? Region.Value : 0; if (regionIndex < 0) regionIndex = 0;
		var hasegg = HasDan.HasValue ? HasDan.Value : 0; if (hasegg < 0) hasegg = 0;
		var haschild = HasRuGe.HasValue ? HasRuGe.Value : 0; if (haschild < 0) haschild = 0;
		var haswendu = WenDu.HasValue ? WenDu.Value : 0; if (haswendu < 0) haswendu = 0;
		var condition = new PigeonCondition
		{
			Region = AreaArray[regionIndex],
			CageNumber = CageNumber,
			CageStatus = CageStatus,
			HasEgg = hasegg,
			HasRuGe = haschild,
			TempStatus = haswendu

		};
		var res = AppRuntime.GetService().GetService<PigeonCageService>().GetPigeonCageQueriyAll(condition);
		var newres = new List<PigeonCageExcel>();
		res.ForEach(x =>
		{
			var tt = new PigeonCageExcel
			{
				Temperature = x.Temperature,
				Id = x.Id,
				Arrange = x.Arrange,
				Building = x.Building,
				DailyGrams = x.DailyGrams,
				EggCount = x.EggCount,
				EggDate = x.EggDate,
				EggDay = x.EggDay,
				Group = x.Group,
				IsFertilization = x.IsFertilization,
				PigeonCount = x.PigeonCount,
				Number = x.Number,
				RuGeCount = x.RuGeCount,
				RuGeDay = x.RuGeDay,
				ChildDate = x.ChildDate,
				PigeonDate = x.PigeonDate,

			};
			newres.Add(tt);
		});
		SaveFileDialog saveFileDialog = new SaveFileDialog();
		saveFileDialog.Filter = "*.xlsx|*.*";
		if (saveFileDialog.ShowDialog() == DialogResult.OK)
		{
			var path = saveFileDialog.FileName;
			if (!path.EndsWith(".xlsx"))
			{
				path += ".xlsx";
			}
			MiniExcel.SaveAs(path, newres);
		}


	}

	[RelayCommand]
	public async Task ImportCage()
	{

		var fileDialog = new OpenFileDialog();
		fileDialog.Filter = "*.xlsx|*.*";
		if (fileDialog.ShowDialog() == DialogResult.OK)
		{
			try
			{
				var path = fileDialog.FileName;
				var datas = MiniExcel.Query<PigeonCageExcel>(path);
				ImportCageData2DB(datas);
			}
			catch (Exception ex)
			{
				Growl.ErrorGlobal(ex.Message);
			}


		}
	}



	public void ImportCageData2DB(IEnumerable<PigeonCageExcel> lst)
	{
		if (lst == null || lst.Count() <= 0) return;
		var cages = new List<PigeonCageQuery>();
		lst.ForEach(x =>
		{
			var tt = new PigeonCageQuery
			{
				Temperature = x.Temperature,
				Id = x.Id,
				Arrange = x.Arrange,
				Building = x.Building,
				DailyGrams = x.DailyGrams,
				EggCount = x.EggCount,
				EggDate = x.EggDate,
				EggDay = x.EggDay,
				Group = x.Group,
				IsFertilization = x.IsFertilization,
				PigeonCount = x.PigeonCount,
				Number = x.Number,
				RuGeCount = x.RuGeCount,
				RuGeDay = x.RuGeDay,
				ChildDate = x.ChildDate,
				PigeonDate = x.PigeonDate,


			};
			cages.Add(tt);

		});
		var res = AppRuntime.GetService().GetService<PigeonCageService>().ImpoertPigeonCageData(cages);
		if (res.IsError)
		{
			Growl.ErrorGlobal(res.msg);
		}
	}


	public void ExportErrorCage()
	{
		var res = AppRuntime.GetService().GetService<AgvCarService>().GetTodayAgvErrorData();
		var first = res.First.Select(x => new AgvErrorFeedData
		{
			CarNumber = x.CarNumber,
			CreateTime = x.CreateTime,
			BarCode = x.BarCode,
			FeedNumber = x.FeedNumber,
			FeedTotal = x.FeedTotal,
			ServoUseStatus = x.ServoUseStatus,
			CageNumber = $"{x.BarCode.Substring(0, 1)}-{x.BarCode.Substring(1, 2)}-{x.BarCode.Substring(3, 3)}-{x.BarCode.Substring(6, 2)}"
		}).ToList();
		var second = res.Second.Select(x => new AgvErrorFeedData
		{
			CarNumber = x.CarNumber,
			CreateTime = x.CreateTime,
			BarCode = x.BarCode,
			FeedNumber = x.FeedNumber,
			FeedTotal = x.FeedTotal,
			ServoUseStatus = x.ServoUseStatus,
			CageNumber = $"{x.BarCode.Substring(0, 1)}-{x.BarCode.Substring(1, 2)}-{x.BarCode.Substring(3, 3)}-{x.BarCode.Substring(6, 2)}"
		}).ToList();
		var third = res.Third.Select(x => new AgvErrorFeedData
		{
			CarNumber = x.CarNumber,
			CreateTime = x.CreateTime,
			BarCode = x.BarCode,
			FeedNumber = x.FeedNumber,
			FeedTotal = x.FeedTotal,
			ServoUseStatus = x.ServoUseStatus,
			CageNumber = $"{x.BarCode.Substring(0, 1)}-{x.BarCode.Substring(1, 2)}-{x.BarCode.Substring(3, 3)}-{x.BarCode.Substring(6, 2)}"
		}).ToList();
		var sheets = new Dictionary<string, object>
		{
			["第一次喂料"] = first,
			["第二次喂料"] = second,
			["第三次喂料"] = third,

		};
		SaveFileDialog saveFileDialog = new SaveFileDialog();
		saveFileDialog.Filter = "*.xlsx|*.*";
		if (saveFileDialog.ShowDialog() == DialogResult.OK)
		{
			var path = saveFileDialog.FileName;
			if (!path.EndsWith(".xlsx"))
			{
				path += ".xlsx";
			}
			MiniExcel.SaveAs(path, sheets);
		}
	}





}
